package cn.mumzone.pos.model.source;

import android.text.TextUtils;
import android.util.ArrayMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.mumzone.basic.net.http.callback.ApiCallBack;
import cn.mumzone.basic.net.response.BaseResponse;
import cn.mumzone.basic.net.response.PageListResponse;
import cn.mumzone.basic.net.source.AbsRepository;
import cn.mumzone.basic.util.MD5Util;
import cn.mumzone.basic.util.RxUtil;
import cn.mumzone.basic.util.SPManager;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.api.ApiRequest;
import cn.mumzone.pos.model.IntegralRoleEntity;
import cn.mumzone.pos.model.LevelListEntity;
import cn.mumzone.pos.model.OffWorkSumAmountEntity;
import cn.mumzone.pos.model.LoginEntity;
import cn.mumzone.pos.model.OffWorkEntity;
import cn.mumzone.pos.model.OffWorkSumAmountResult;
import cn.mumzone.pos.model.OffWorkTicketEntity;
import cn.mumzone.pos.model.PopupHintEntity;
import cn.mumzone.pos.model.ShopUserEntity;
import cn.mumzone.pos.model.UserPermissionEntity;
import cn.mumzone.pos.model.VerifyReturnAuthEntity;
import cn.mumzone.pos.util.PopupUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Response;

import static cn.mumzone.pos.model.source.MemberRepository.SP_KEY_MEMBER_LEVEL;


/**
 * Created by lijiateng on 2018/12/10.
 * <p>
 * 用户相关联网仓库类
 */

public class UserRepository extends AbsRepository {

    //用户token
    private static final String SP_KEY_USER_TOKEN = "user_token";
    //用户ID
    private static final String SP_KEY_USER_ID = "user_id";
    //用户名
    private static final String SP_KEY_USER_NAME = "user_name";
    //门店类型
    private static final String SP_KEY_ORG_CODE = "org_code";
    //门店ID
    private static final String SP_KEY_SHOP_ID = "shop_id";
    //公司ID
    private static final String SP_KEY_COMPANY_ID = "companyId";
    //门店名称
    private static final String SP_KEY_SHOP_NAME = "shop_name";
    //设备型号
    private static final String SP_KEY_EQUI_MODEL = "equiModel";
    //登录人手机号
    private static final String SP_KEY_USER_LOGIN_PHONE = "user_login_phone";
    //登录时间
    private static final String SP_KEY_USER_LOGIN_TIME = "user_login_time";
    //业务范围
    private static final String SP_KEY_BUSINESS_SCOPE = "operationScope";
    //门店电话
    private static final String SP_KEY_SHOP_PHONE = "shop_phone";
    //门店地址
    private static final String SP_KEY_SHOP_ADDRESS = "shop_address";
    //门店资金归属
    private static final String SP_KEY_STORE_TYPE = "store_type";
    //门店支付渠道
    private static final String SP_KEY_PAY_CNL = "pay_cnl";
    //用户权限
    private static final String SP_KEY_USER_PERMISSION = "user_permission";

    private static final String SP_KEY_INTEGRAL_DISCOUNT = "use_integral_discount";
    private static final String SP_KEY_REDEEM_GOODS = "use_redeem_goods";


    public void getUserInfo(String phone, String pwd, String posSNCode, ApiCallBack<LoginEntity> callBack) {

        ApiRequest.getUserService()
                .getUserInfo(phone, MD5Util.md5ForStr(pwd), posSNCode)
                .compose(RxUtil.<Response<BaseResponse<LoginEntity>>>applySchedulers())
                .subscribe(callBack);

    }


    public void verifyReturnAuth(String userId, String userName, String passWord, ApiCallBack<VerifyReturnAuthEntity> callBack) {

        ApiRequest.getUserService()
                .verifyReturnAuth(userId, userName, passWord)
                .compose(RxUtil.<Response<BaseResponse<VerifyReturnAuthEntity>>>applySchedulers())
                .subscribe(callBack);

    }

    public void getShopUserList(ApiCallBack<PageListResponse<ShopUserEntity>> callBack) {
        ApiRequest.getUserService()
                .getShopUserList("1", "30")
                .compose(RxUtil.<Response<BaseResponse<PageListResponse<ShopUserEntity>>>>applySchedulers())
                .subscribe(callBack);
    }


    public void offWorkSumAmount(ApiCallBack<OffWorkSumAmountResult> callBack) {
        ApiRequest.getUserService()
                .offWorkSumAmount()
                .compose(RxUtil.<Response<BaseResponse<OffWorkSumAmountResult>>>applySchedulers())
                .subscribe(callBack);
    }


    public void shiftExchange(String cashAmount, ApiCallBack<String> callBack) {
        ApiRequest.getUserService()
                .shiftExchange(AppConstants.TEMP_SHOP_NAME, cashAmount)
                .compose(RxUtil.<Response<BaseResponse<String>>>applySchedulers())
                .subscribe(callBack);
    }

    public void updatePwd(String originPwd, String newPwd, ApiCallBack<String> callBack) {
        ApiRequest.getUserService()
                .updatePwd(MD5Util.string2MD5(originPwd), MD5Util.string2MD5(newPwd))
                .compose(RxUtil.<Response<BaseResponse<String>>>applySchedulers())
                .subscribe(callBack);

    }

    public void getSchedulePermission(ApiCallBack<String> callBack) {
        ApiRequest.getUserService()
                .getSchedulePermission()
                .compose(RxUtil.<Response<BaseResponse<String>>>applySchedulers())
                .subscribe(callBack);

    }

    public void getOffWorkRecord(String startTime, String endTime, String key, String pageNum, ApiCallBack<PageListResponse<OffWorkEntity>> callBack) {
        ApiRequest.getUserService()
                .getShiftListPage(startTime, endTime, key, pageNum, "30")
                .compose(RxUtil.<Response<BaseResponse<PageListResponse<OffWorkEntity>>>>applySchedulers())
                .subscribe(callBack);
    }

    public void getShiftRecordDetail(String id, ApiCallBack<OffWorkTicketEntity> callBack) {
        ApiRequest.getUserService()
                .getShiftRecordDetail(id)
                .compose(RxUtil.<Response<BaseResponse<OffWorkTicketEntity>>>applySchedulers())
                .subscribe(callBack);
    }


    public void saveUserInfo(LoginEntity entity) {
        //用户token
        mSPManager.put(SP_KEY_USER_TOKEN, entity.getToken());
        //用户ID
        mSPManager.put(SP_KEY_USER_ID, entity.getId());
        //用户名
        mSPManager.put(SP_KEY_USER_NAME, entity.getName());
        //门店ID
        mSPManager.put(SP_KEY_SHOP_ID, entity.getShopId());
        //门店类型
        mSPManager.put(SP_KEY_ORG_CODE, entity.getOrgCode());
        //门店名称
        mSPManager.put(SP_KEY_SHOP_NAME, entity.getShopName());
        //公司ID
        mSPManager.put(SP_KEY_COMPANY_ID, entity.getCompanyId());
        //用户手机号
        mSPManager.put(SP_KEY_USER_LOGIN_PHONE, entity.getPhone());
        //业务范围
        mSPManager.put(SP_KEY_BUSINESS_SCOPE,
                TextUtils.isEmpty(entity.getBusinessScope()) ? "0,1" : entity.getBusinessScope());
        //资金归属
        mSPManager.put(SP_KEY_STORE_TYPE, entity.getStoreType());
        //支付渠道
        mSPManager.put(SP_KEY_PAY_CNL, entity.getPayCnl());
        //登录时间
        mSPManager.put(SP_KEY_USER_LOGIN_TIME, String.valueOf(System.currentTimeMillis()));
        //设备型号
        mSPManager.put(SP_KEY_EQUI_MODEL, StringUtils.getString(entity.getEquiModel()));
        //门店电话
        mSPManager.put(SP_KEY_SHOP_PHONE, StringUtils.getString(entity.getShopPhone()));
        //门店地址
        mSPManager.put(SP_KEY_SHOP_ADDRESS, StringUtils.getString(entity.getShopAddress()));

        mSPManager.putJson(SP_KEY_USER_PERMISSION, entity.getPermission());

        if (TextUtils.isEmpty(mSPManager.getString(entity.getId()))) {
            // 如果为空，说明是首次登陆，需要初始化 Popup 数据
            mSPManager.put(entity.getId(), JSON.toJSONString(new PopupHintEntity()));
        }

        // 用户 popup 缓存数据
        AppConstants.USER_POPUP_HINT = mSPManager.getString(entity.getId());
        AppConstants.ALL_HINT_DISMISSED = false;

        PopupUtil.hintEntity = JSON.parseObject(AppConstants.USER_POPUP_HINT, PopupHintEntity.class);

        // 更新内存数据
        AppConstants.TEMP_TOKEN = entity.getToken();
        AppConstants.TEMP_COMPANY_ID = entity.getCompanyId();
        AppConstants.TEMP_SHOP_ID = entity.getShopId();
        AppConstants.TEMP_USER_NAME = entity.getName();
        AppConstants.TEMP_SELLER_ID = entity.getId();
        AppConstants.TEMP_SHOP_NAME = entity.getShopName();
        AppConstants.TEMP_EQUI_MODEL = entity.getEquiModel();
        AppConstants.TEMP_SHOP_PHONE = entity.getShopPhone();
        AppConstants.TEMP_SHOP_ADDRESS = entity.getShopAddress();
        AppConstants.TEMP_SHOP_STORE_TYPE = entity.getStoreType();
        AppConstants.TEMP_SHOP_PAY_CNL = entity.getPayCnl();
        AppConstants.TEMP_BUSINESS_SCOPE = entity.getBusinessScope();
        AppConstants.TEMP_USER_PERMISSION = entity.getPermission();

    }

    public void clearUserInfo() {
        //引导气泡，以用户id为key，需要先清空
        mSPManager.put(mSPManager.getString(SP_KEY_USER_ID), "");
        //用户token
        mSPManager.put(SP_KEY_USER_TOKEN, "");
        //用户ID
        mSPManager.put(SP_KEY_USER_ID, "");
        //用户名
        mSPManager.put(SP_KEY_USER_NAME, "");
        //门店ID
        mSPManager.put(SP_KEY_SHOP_ID, "");
        //门店类型
        mSPManager.put(SP_KEY_ORG_CODE, "");
        //门店名称
        mSPManager.put(SP_KEY_SHOP_NAME, "");
        //公司ID
        mSPManager.put(SP_KEY_COMPANY_ID, "");
        //用户手机号
        mSPManager.put(SP_KEY_USER_LOGIN_PHONE, "");
        //业务范围
        mSPManager.put(SP_KEY_BUSINESS_SCOPE, "");
        //登录时间
        mSPManager.put(SP_KEY_USER_LOGIN_TIME, "");
        //设备型号
        mSPManager.put(SP_KEY_EQUI_MODEL, "");
        //会员等级
        mSPManager.put(SP_KEY_MEMBER_LEVEL, "");
        //门店电话
        mSPManager.put(SP_KEY_SHOP_PHONE, "");
        //门店地址
        mSPManager.put(SP_KEY_SHOP_ADDRESS, "");
        //用户权限
        mSPManager.put(SP_KEY_USER_PERMISSION, "");
        //资金归属
        mSPManager.put(SP_KEY_STORE_TYPE, LoginEntity.STORE_TYPE_SHOP);
        //支付渠道
        mSPManager.put(SP_KEY_PAY_CNL, LoginEntity.PAY_CNL_NATIVE);
        //抵现
        mSPManager.put(SP_KEY_INTEGRAL_DISCOUNT, "");
        //换购
        mSPManager.put(SP_KEY_REDEEM_GOODS, "");

        //不清空门店名称、用户名、pos机型号等字段、用于交班打印小票，待用户关闭App 数据自然清空
        AppConstants.TEMP_TOKEN = "";
        AppConstants.TEMP_COMPANY_ID = "";
        AppConstants.TEMP_SHOP_ID = "";
        AppConstants.TEMP_SELLER_ID = "";
        AppConstants.TEMP_MEMBER_LEVEL = "";
        AppConstants.TEMP_USER_PERMISSION = null;
        AppConstants.TEMP_SHOP_STORE_TYPE = LoginEntity.STORE_TYPE_SHOP;
        AppConstants.TEMP_SHOP_PAY_CNL = LoginEntity.PAY_CNL_NATIVE;
        AppConstants.USER_POPUP_HINT = "";
        AppConstants.ALL_HINT_DISMISSED = false;

    }


    public void saveIntegralRole(IntegralRoleEntity roleEntity) {
        mSPManager.put(SP_KEY_INTEGRAL_DISCOUNT, StringUtils.get(roleEntity.getIsAtCash(), "0"));
        mSPManager.put(SP_KEY_REDEEM_GOODS, StringUtils.get(roleEntity.getIsIntegralGood(), "0"));

        AppConstants.TEMP_IS_INTEGRAL_DISCOUNT = StringUtils.get(roleEntity.getIsAtCash(), "0");
        AppConstants.TEMP_IS_REDEEM_GOODS = StringUtils.get(roleEntity.getIsIntegralGood(), "0");
    }


    public LoginEntity getLoginInfo() {
        LoginEntity loginEntity = new LoginEntity();
        loginEntity.setToken(mSPManager.getString(SP_KEY_USER_TOKEN));
        loginEntity.setCompanyId(mSPManager.getString(SP_KEY_COMPANY_ID));
        loginEntity.setShopId(mSPManager.getString(SP_KEY_SHOP_ID));
        loginEntity.setId(mSPManager.getString(SP_KEY_USER_ID));
        loginEntity.setShopName(mSPManager.getString(SP_KEY_SHOP_NAME));
        loginEntity.setName(mSPManager.getString(SP_KEY_USER_NAME));
        loginEntity.setBusinessScope(mSPManager.getString(SP_KEY_BUSINESS_SCOPE));
        loginEntity.setEquiModel(mSPManager.getString(SP_KEY_EQUI_MODEL));
        loginEntity.setLevelList(mSPManager.getString(SP_KEY_MEMBER_LEVEL));
        loginEntity.setShopPhone(mSPManager.getString(SP_KEY_SHOP_PHONE));
        loginEntity.setShopAddress(mSPManager.getString(SP_KEY_SHOP_ADDRESS));
        loginEntity.setPermission(mSPManager.getJson(SP_KEY_USER_PERMISSION, UserPermissionEntity.class));
        loginEntity.setStoreType(mSPManager.getInt(SP_KEY_STORE_TYPE, LoginEntity.STORE_TYPE_SHOP));
        loginEntity.setPayCnl(mSPManager.getInt(SP_KEY_PAY_CNL, LoginEntity.PAY_CNL_NATIVE));
        loginEntity.setIsIntegral(mSPManager.getString(SP_KEY_INTEGRAL_DISCOUNT));
        loginEntity.setIsRedeem(mSPManager.getString(SP_KEY_REDEEM_GOODS));
        loginEntity.setPopHint(mSPManager.getString(loginEntity.getId()));
        loginEntity.setAllHintDismissed(ifAllHintDismissed(loginEntity.getPopHint()));
        return loginEntity;
    }

    private boolean ifAllHintDismissed(String popHintJson) {
        PopupHintEntity entity = JSON.parseObject(popHintJson, PopupHintEntity.class);
        if (entity == null) {
            return false;
        }

        Field[] fields = entity.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                if (!field.getBoolean(entity)) {
                    return false;
                }
            } catch (Exception e) {
                return false;
            }
        }

        return true;
    }

    private String loadUpPopupHintData() {
        List<PopupHintEntity> hintList = new ArrayList<>();

        return JSON.toJSONString(hintList);
    }

    public void getAllIntegralRuleInfo(ApiCallBack<IntegralRoleEntity> callBack) {
        ApiRequest.getUserService()
                .getAllIntegralRuleInfo()
                .compose(RxUtil.<Response<BaseResponse<IntegralRoleEntity>>>applySchedulers())
                .subscribe(callBack);

    }

}
